package cn.ulyer.core.secure.filter;

import cn.hutool.core.util.StrUtil;
import cn.ulyer.common.constants.ResultCode;
import cn.ulyer.common.utils.Result;
import cn.ulyer.common.utils.WebUtils;
import cn.ulyer.core.secure.service.TokenService;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/***
 * @author: ulyer
 * @Date: 2021/8/11
 * @Description: jwtFilter
 */
public class JwtFilterAuthenticationTokenFilter extends OncePerRequestFilter {

    private TokenService tokenService;

    public JwtFilterAuthenticationTokenFilter(TokenService tokenService){
        this.tokenService = tokenService;
    }





    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = (String) tokenService.readToken(httpServletRequest);
        if(StrUtil.isNotBlank(token)){
            try{
                Authentication authentication = tokenService.authenticate(token);
                if(authentication!=null&&authentication.isAuthenticated()){
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }catch (AuthenticationException e){
                httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
                WebUtils.writeJson(httpServletResponse, JSON.toJSONString(Result.fail(ResultCode.AUTHORIZE_FAIL).message(e.getMessage())));
                return;
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
